package com.example.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.example.config.exception.GlobalExcetion;
import com.example.ribbon.service.SysTableRibbonService;
import com.example.system.domain.SysTableScript;
import com.example.system.domain.SysTableScriptExt;
import com.example.system.service.SysTableScriptExtService;
import com.example.system.service.SysTableScriptService;
import com.example.system.vo.SysTableScriptExtVo;
import com.example.util.Results;
import com.example.util.StringSplitUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/tableext")
public class SystemTableScriptExtController {

    @Autowired
    private SysTableScriptService sysTableScriptService;

    @Autowired
    private SysTableScriptExtService sysTableScriptExtService;

    @Autowired
    private SysTableRibbonService sysTableRibbonService;

    @PostMapping("/addtableext")
    public JSONObject addTableExt(@RequestBody SysTableScriptExtVo vo) throws GlobalExcetion {
        SysTableScript sysTableScript=sysTableScriptService.getById(vo.getTableId());
        if(sysTableScript==null){
            throw new GlobalExcetion(1,"系统表不存在");
        }
        SysTableScriptExt sysTableScriptExt=new SysTableScriptExt();
        BeanUtils.copyProperties(vo,sysTableScriptExt);
        sysTableScriptExt.setTableNo(sysTableScript.getTableNo());
        sysTableScriptExt.setTableName(sysTableScript.getTableName());
        sysTableScriptExt.setTableStatus(1);
        sysTableScriptExt.setCreateTime(new Date());
        sysTableScriptExt.setCreateTime(new Date());
        sysTableScriptExt.setUpdateTime(new Date());
        sysTableScriptExt.setServerName(sysTableScript.getServerName());
        sysTableScriptExtService.save(sysTableScriptExt);
        return Results.success("成功");
    }

    @GetMapping("/gettableext")
    public SysTableScriptExt getTableExt(@RequestParam("uuid") String uuid) throws GlobalExcetion {
        SysTableScriptExt sysTableScriptExt=sysTableScriptExtService.getById(uuid);
        return sysTableScriptExt;
    }

    @GetMapping("/pushnodeext")
    public JSONObject pushNodeExt() throws GlobalExcetion {
        List<SysTableScriptExt> extList=sysTableScriptExtService.getList();
        if(extList==null||extList.size()==0){
            return Results.error("暂无可执行数据");
        }
        for(SysTableScriptExt ext:extList){
            List<String> serverNames= StringSplitUtil.splitToList(ext.getServerName());
            for(String serverName:serverNames){
                sysTableRibbonService.pushSysTableExtToNode(serverName,ext.getUuid());
                ext.setTableStatus(0);
                this.sysTableScriptExtService.updateById(ext);
            }
        }
        return Results.success("执行成功");
    }

}
